<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
  const mainAlertField = enableTranslation ? 'translationKey' : 'message';
_%>
<%_ if (clientTestFrameworkVitest) { _%>
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
<%_ } _%>
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
<%_ if (enableTranslation) { _%>
import { TranslateModule } from '@ngx-translate/core';
<%_ } _%>

import { EventManager } from 'app/core/util/event-manager.service';
import { AlertModel, AlertService } from 'app/core/util/alert.service';

import { AlertError } from './alert-error';

describe('Alert Error Component', () => {
  let comp: AlertError;
  let fixture: ComponentFixture<AlertError>;
  let eventManager: EventManager;
  let alertService: AlertService;

  beforeEach(
    () => {
      TestBed.configureTestingModule({
        imports: [
<%_ if (enableTranslation) { _%>
          TranslateModule.forRoot(),
<%_ } _%>
        ],
        providers: [EventManager, AlertService],
      });
    }
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(AlertError);
    comp = fixture.componentInstance;
    eventManager = TestBed.inject(EventManager);
    alertService = TestBed.inject(AlertService);
    alertService.addAlert = (alert: AlertModel, alerts?: AlertModel[]) => {
      if (alerts) {
        alerts.push(alert);
      }
      return alert;
    };
  });

  describe('Error Handling', () => {
    it('should display an alert on status 0', () => {
      // GIVEN
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: { status: 0 } });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe(<% if (enableTranslation) { %>'error.server.not.reachable'<% } else { %>'Server not reachable'<% } %>);
    });

    it('should display an alert on status 404', () => {
      // GIVEN
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: { status: 404 } });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe(<% if (enableTranslation) { %>'error.url.not.found'<% } else { %>'Not found'<% } %>);
    });

    it('should display an alert on generic error', () => {
      // GIVEN
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: { error: { message: 'Error Message' } } });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: { error: 'Second Error Message' } });
      // THEN
      expect(comp.alerts().length).toBe(2);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe('Error Message');
      expect(comp.alerts()[1].<%= mainAlertField %>).toBe('Second Error Message');
    });

    it('should display an alert on status 400 for generic error', () => {
      // GIVEN
      const response = new HttpErrorResponse({
        url: 'http://localhost:8080/api/foos',
        headers: new HttpHeaders(),
        status: 400,
        statusText: 'Bad Request',
        error: {
          type: 'https://www.jhipster.tech/problem/problem-with-message',
          title: 'Bad Request',
          status: 400,
          path: '/api/foos',
          message: 'error.validation',
        },
      });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: response });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe('error.validation');
    });

    it('should display an alert on status 400 for generic error without message', () => {
      // GIVEN
      const response = new HttpErrorResponse({
        url: 'http://localhost:8080/api/foos',
        headers: new HttpHeaders(),
        status: 400,
        error: 'Bad Request',
      });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: response });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe('Bad Request');
    });

    it('should display an alert on status 400 for invalid parameters', () => {
      // GIVEN
      const response = new HttpErrorResponse({
        url: 'http://localhost:8080/api/foos',
        headers: new HttpHeaders(),
        status: 400,
        statusText: 'Bad Request',
        error: {
          type: 'https://www.jhipster.tech/problem/problem-with-message',
          title: 'Method argument not valid',
          status: 400,
          path: '/api/foos',
          message: 'error.validation',
          fieldErrors: [{ objectName: 'foo', field: 'minField', message: 'Min' }],
        },
      });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: response });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe(<% if (enableTranslation) { %>'error.Size'<% } else { %>'Error on field "MinField"'<% } %>);
    });

    it('should display an alert on status 400 for error headers', () => {
      // GIVEN
      const response = new HttpErrorResponse({
        url: 'http://localhost:8080/api/foos',
        headers: new HttpHeaders().append('app-error', 'Error Message').append('app-params', 'foo'),
        status: 400,
        statusText: 'Bad Request',
        error: {
          status: 400,
          message: 'error.validation',
        },
      });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: response });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe('Error Message');
    });

    it('should display an alert on status 500 with detail', () => {
      // GIVEN
      const response = new HttpErrorResponse({
        url: 'http://localhost:8080/api/foos',
        headers: new HttpHeaders(),
        status: 500,
        statusText: 'Internal server error',
        error: {
          status: 500,
          message: 'error.http.500',
          detail: 'Detailed error message',
        },
      });
      eventManager.broadcast({ name: '<%= frontendAppName %>.httpError', content: response });
      // THEN
      expect(comp.alerts().length).toBe(1);
      expect(comp.alerts()[0].<%= mainAlertField %>).toBe(<% if (enableTranslation) { %>'error.http.500'<% } else { %>'Detailed error message'<% } %>);
    });
  });
});
